import 'dart:io';

import 'package:device_info_plus/device_info_plus.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:hktk_app/dao/download_dao.dart';
import 'package:hktk_app/dao/login_dao.dart';
import 'package:hktk_app/dao/my_dao.dart';
import 'package:hktk_app/exception/dao_exception.dart';
import 'package:hktk_app/ienum/package/payment_type_enum.dart';
import 'package:hktk_app/model/login/config_model.dart';
import 'package:hktk_app/model/my/version_model.dart';
import 'package:hktk_app/pages/mine/update_password_page.dart';
import 'package:hktk_app/painter/line_painter.dart';
import 'package:hktk_app/util/device_util.dart';
import 'package:hktk_app/util/font_util.dart';
import 'package:hktk_app/util/my_util.dart';
import 'package:hktk_app/util/toast_util.dart';
import 'package:hktk_app/util/view_util.dart';
import 'package:hktk_app/widget/page_title_widget.dart';

/// 设置页面
class SetUpPage extends StatefulWidget {
  const SetUpPage({super.key});

  @override
  State<SetUpPage> createState() => _SetUpPageState();
}

class _SetUpPageState extends State<SetUpPage> {
  late BuildContext _context;

  /// 初始化数据方法
  late Future<Map<String, dynamic>> _futureInit;

  /// 缓存数据
  late double _cache;

  /// 版本数据方法
  late String _edition;

  /// 系统版本数据
  late VersionModel _versionModel;

  /// 是否显示新版本
  late bool _newVersion;

  /// 用户协议和隐私政策
  late AppConfig _appConfig;

  late String operateSystemName;

  late String operatingSystemVersion;

  @override
  void initState() {
    super.initState();





    // operatingSystemVersion = Platform.operatingSystemVersion;

    _cache = 0;
    _edition = "";
    _versionModel = VersionModel();
    _appConfig = AppConfig();
    _newVersion = false;

    /// 初始化数据方法
    _futureInit = () async {







      Map<String, dynamic> map = {};
      try {
        // 计算缓存
        _cache = await DownloadDao.loadApplicationCache();
        // 获取版本号
        _edition = await DownloadDao.getAppVersion();
        DeviceTypeEnum type = DeviceTypeEnum.android;
        if (Platform.isIOS) type = DeviceTypeEnum.ios;
        // 获取系统当前版本号
        _versionModel = await MyDao.versionCurrent(type: type);
        // 判断是否需要更新
        _judgeNewVersion();
        // 获取用户协议和隐私政策
        ConfigModel? model = await LoginDao.config();
        if (model != null) {
          _appConfig = model.appConfig!;
        }

        map["suc"] = true;

        DeviceUtil.deviceInit();
        if (Platform.isAndroid) {
          if (Platform.operatingSystem == "harmonyos") {
            operateSystemName = "鸿蒙";
          } else {
            operateSystemName = "安卓";
          }

          var deviceInfo=await DeviceUtil.getAndroidDeviceInfo();

          operatingSystemVersion=deviceInfo.version.release;
          // 获取Android SDK版本号
          // operatingSystemVersion= '${deviceInfo.version.sdkInt}';
        } else if (Platform.isIOS) {
          operateSystemName = "苹果";
          var deviceInfo=await DeviceUtil.getIosDeviceInfo();
          // 获取iOS系统版本
          operatingSystemVersion=  deviceInfo.systemVersion;
        }
      } catch (e) {
        map = {"suc": false, "msg": "未知错误，请重试"};
        if (e is DaoException) {
          map["msg"] = e.msg;
        }
      }
      return map;
    }();
  }

  @override
  void dispose() {
    super.dispose();
    ToastUtil.loadingBoxRemove();
  }

  Future<Map<String, dynamic>> getDetailedAndroidInfo() async {
    if (Platform.isAndroid) {
      DeviceInfoPlugin deviceInfo = DeviceInfoPlugin();
      AndroidDeviceInfo androidInfo = await deviceInfo.androidInfo;

      return {
        'sdkInt': androidInfo.version.sdkInt,
        'release': androidInfo.version.release,
        'codename': androidInfo.version.codename,
        'incremental': androidInfo.version.incremental,
      };
    }
    return {};
  }

  @override
  Widget build(BuildContext context) {
    _context = context;
    return Scaffold(
      backgroundColor: colorWhite2,
      body: SafeArea(
          child: Column(
        children: [
          PageTitleWidget(name: "设置", pageContext: context),
          Expanded(child: _futureItem()),
        ],
      )),
    );
  }

  /// 加载数据方法
  _futureItem() {
    return FutureBuilder<Map<String, dynamic>>(
      future: _futureInit,
      builder: (
        BuildContext context,
        AsyncSnapshot<Map<String, dynamic>> snapshot,
      ) {
        if (snapshot.connectionState == ConnectionState.done) {
          Map<String, dynamic> map = snapshot.data!;
          if (!map['suc']) {
            WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
              ToastUtil.show(context: _context, msg: map["msg"]);
            });
          }
          return _content();
        } else {
          return const Center(
            child: CircularProgressIndicator(),
          );
        }
      },
    );
  }

  /// 判断版本是否需要升级
  void _judgeNewVersion() {
    if (_versionModel.verify == false && _versionModel.version != null) {
      String ver = _versionModel.version!;
      int edition = int.parse(_edition.replaceAll(".", ""));
      int ver2 = int.parse(ver.replaceAll(".", ""));
      _newVersion = ver2 > edition;
    }
  }

  /// 内容方法
  _content() {
    double bottom = ScreenUtil().bottomBarHeight;
    double recordBottom = bottom + 88;
    return Stack(
      children: [
        _listItems(),
        Positioned(
          left: 30,
          bottom: bottom + 30,
          child: _btnItem(),
        ),
        Positioned(
          bottom: recordBottom,
          child: _recordKeepingItem(),
        )
      ],
    );
  }

  /// 按钮组件
  _btnItem() {
    return GestureDetector(
      onTap: _onTapFunTcdl,
      child: Container(
        width: 1.sw - 60,
        padding: EdgeInsets.symmetric(vertical: 5),
        decoration: BoxDecoration(
          color: colorBlue1,
          borderRadius: BorderRadius.circular(49),
        ),
        child: Center(
          child: Text(
            "退出登录",
            style: FontUtil.fontWhile1(22),
          ),
        ),
      ),
    );
  }

  /// 设置相关内容
  _listItems() {
    double bottom = ScreenUtil().bottomBarHeight;
    double bot = bottom + 30 + 88 + 30 + 80 + 24;
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 24),
      child: MediaQuery.removePadding(
        removeTop: true,
        context: _context,
        child: ListView(
          children: [
            hiSpace(height: 24),
            _viewItems(),
            hiSpace(height: bot),
          ],
        ),
      ),
    );
  }

  /// 内容展示
  _viewItems() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 20),
      decoration: BoxDecoration(
        color: colorWhite1,
        borderRadius: BorderRadius.circular(20),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          _defaultItem(
            svgUrl: "images/my/set_up_update.svg",
            title: "修改密码",
            onTapFun: _onTapFunXgmm,
          ),
          _dashedLine(),
          _defaultItem(
            svgUrl: "images/my/set_up_zxzh.svg",
            title: "注销账号",
            onTapFun: _onTapFunZxzh,
          ),
          _dashedLine(),
          _defaultItem(
            svgUrl: "images/my/set_up_qchc.svg",
            title: "清除缓存",
            onTapFun: _onTapFunQchc,
            rightTips: DownloadDao.formatSize(_cache),
          ),
          _dashedLine(),
          _defaultItem(
            svgUrl: "images/my/set_up_bbsj.svg",
            title: "版本升级",
            onTapFun: _onTapFunBbsj,
            rightTips: _newVersion ? _versionModel.version : _edition,
            leftZdy: _newVersion ? _editionIcon() : null,
          ),
          _dashedLine(),
          _defaultItem(
            svgUrl: "images/question/bottom_jx.svg",
            title: "用户协议",
            onTapFun: _onTapFunYhxy,
          ),
          _dashedLine(),
          _defaultItem(
            svgUrl: "images/question/bottom_jx.svg",
            title: "隐私政策",
            onTapFun: _onTapFunYszc,
          ),
          _dashedLine(),
          _defaultItem(
            svgUrl: "images/question/bottom_jx.svg",
            title: "$operateSystemName版本:$operatingSystemVersion",
            onTapFun: () {},
          ),
          _dashedLine(),
          _defaultItem(
            svgUrl: "images/question/bottom_jx.svg",
            title: "下个版本",
            onTapFun: () {
              ToastUtil.show(context: _context, msg: "开始接入采集客户端错误日志，持续优化");
            },
          ),
        ],
      ),
    );
  }

  /// 虚线分割
  _dashedLine() {
    return CustomPaint(
      painter: LinePainter(
        color: colorGrey14,
        length: 1.sw - (44 * 2),
        isDashed: true,
      ),
    );
  }

  /// 默认样式显示
  _defaultItem({
    required String svgUrl,
    required String title,
    required Function() onTapFun,
    String? rightTips,
    Widget? leftZdy,
  }) {
    return GestureDetector(
      onTap: onTapFun,
      // 点击整个区域都会响应
      behavior: HitTestBehavior.opaque,
      child: Padding(
        padding: EdgeInsets.symmetric(vertical: 16),
        // height: 80,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            _leftItem(svgUrl, title, leftZdy),
            _rightItem(rightTips),
          ],
        ),
      ),
    );
  }

  /// 左边标题显示
  _leftItem(String svgUrl, String title, Widget? leftZdy) {
    return Row(
      mainAxisSize: MainAxisSize.min,
      children: [
        SvgPicture.asset(
          svgUrl,
          width: 28,
          height: 28,
          color: colorGrey1,
        ),
        hiSpace(width: 10),
        Text(
          title,
          style: FontUtil.fontBlack1(18),
        ),
        if (leftZdy != null) leftZdy,
      ],
    );
  }

  /// 右边组件显示
  _rightItem(String? rightTips) {
    return Row(
      mainAxisSize: MainAxisSize.min,
      children: [
        if (rightTips != null)
          Text(
            rightTips,
            style: FontUtil.fontGrey15(18),
          ),
        SvgPicture.asset(
          "images/my/activation_icon.svg",
          width: 24,
          height: 24,
        ),
      ],
    );
  }

  /// 版本升级图标
  _editionIcon() {
    return Container(
      margin: EdgeInsets.only(left: 10),
      child: SvgPicture.asset(
        "images/my/set_up_bate.svg",
        width: 46,
        height: 28,
      ),
    );
  }

  /// 注销帐户方法
  _logOffFun() {
    // 打开加载框
    ToastUtil.loadingBoxShow(_context);
    // 开始注销
    _futureLogOff().then((Map<String, dynamic> map) {
      // 关闭加载框
      ToastUtil.loadingBoxRemove();
      // 判断是否成功注销
      if (map["suc"]) {
        // 成功注销，跳转登录页
        Navigator.pushNamedAndRemoveUntil(
          _context,
          "/login",
          (route) => false,
        );
      } else {
        // 注销失败，提示
        ToastUtil.show(context: _context, msg: map["msg"]);
      }
    });
  }

  /// 注销调用方法
  Future<Map<String, dynamic>> _futureLogOff() async {
    Map<String, dynamic> map = {};
    try {
      bool log = await MyDao.logoff();
      map["suc"] = log;
      map["msg"] = log ? "注销成功" : "注销失败";
    } catch (e) {
      map = {"suc": false, "msg": "未知错误，请重试"};
      if (e is DaoException) {
        map["msg"] = e.msg;
      }
    }
    return map;
  }

  /// 清除缓存,只是清除缓存文件，其他的缓存数据没删除
  _clearCache() async {
    // 开启加载框
    ToastUtil.loadingBoxShow(_context);
    // 清除数据
    DownloadDao.clearApplicationCache().then((value) {
      ToastUtil.loadingBoxRemove();
      ToastUtil.show(context: _context, msg: "清除完成");
      setState(() {
        _cache = 0;
      });
    }).catchError((e) {
      ToastUtil.loadingBoxRemove();
      ToastUtil.show(context: _context, msg: "未知错误，请重试");
    });
  }

  /// 退出登录点击方法
  _onTapFunTcdl() {
    loginOut(context);
  }

  /// 修改密码点击方法
  _onTapFunXgmm() {
    Navigator.pushNamed(_context, "/updatePassword");
  }

  /// 注销帐号点击方法
  _onTapFunZxzh() {
    // 弹出对话框询问是否注销
    ToastUtil.showDialogBox(
      context: _context,
      contentText: "请确认是否注销账号，账号注销所有记录都会清除并且不可登录。",
    ).then((bool? value) {
      if (value != null && value) {
        _logOffFun();
      }
    });
  }

  /// 清除缓存点击方法
  _onTapFunQchc() {
    if (_cache > 0) {
      _clearCache();
    } else {
      ToastUtil.show(context: _context, msg: "暂无缓存");
    }
  }

  /// 版本升级点击方法
  _onTapFunBbsj() {
    if (_newVersion) {
      if (Platform.isIOS) {
        // ios 跳转 appStore 安装
      } else if (Platform.isAndroid) {
        // android 应用内更新
        // _androidCheckUpdate();
      }
    }
  }

  /// 用户协议点击方法
  _onTapFunYhxy() {
    if (_appConfig.yhxy != null) {
      Navigator.pushNamed(_context, "/h5", arguments: {
        "url": _appConfig.yhxy!,
        "title": "用户协议",
        "showClose": false,
        "btnPadding": 0.0 as double,
      });
    } else {
      ToastUtil.show(context: _context, msg: "加载失败，数据缺失");
    }
  }

  /// 隐私政策点击方法
  _onTapFunYszc() {
    if (_appConfig.ysxy != null) {
      Navigator.pushNamed(_context, "/h5", arguments: {
        "url": _appConfig.ysxy!,
        "title": "隐私政策",
        "showClose": false,
        "btnPadding": 0.0,
      });
    } else {
      ToastUtil.show(context: _context, msg: "加载失败，数据缺失");
    }
  }

  /// 备案显示
  _recordKeepingItem() {
    double width = ScreenUtil().screenWidth;
    return SizedBox(
      width: width,
      height: 80,
      child: Column(
        // mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          _recordItem(),
          hiSpace(height: 10),
          _companyItem(),
        ],
      ),
    );
  }

  _recordItem() {
    return Text(
      "APP备案编号：渝ICP备2025048867号-2A",
      style: FontUtil.fontGrey1(15),
    );
  }

  /// 公司名称显示
  _companyItem() {
    return Text(
      "公司名称：中震（重庆）网络有限公司",
      style: FontUtil.fontGrey1(15),
    );
  }
}
